// src/demo/error.filter.ts
import { ArgumentsHost, Catch, ExceptionFilter } from "@nestjs/common";

@Catch() // @Catch() 捕获所有异常，也可指定具体异常类型（如 @Catch(Error)
export class ErrorFilter implements ExceptionFilter {
  // 异常过滤器的 catch 方法才是处理异常的地方
  catch(exception: unknown, host: ArgumentsHost) {
    console.error('ErrorFilter 捕获到异常:', exception);

    // 切换到 HTTP 上下文
    const httpContext = host.switchToHttp();
    const request = httpContext.getRequest();
    const response = httpContext.getResponse();

    console.log('请求 URL:', request.url);
    // 返回自定义错误响应
    response.status(500).json({
      statusCode: 500,
      message: 'Server Internal Error',
      detail: exception instanceof Error ? exception.message : 'Unknown Error'
    });
  }
}